package com.liuweiheng.base.handler;

import com.liuweiheng.base.entity.R;
import com.liuweiheng.base.exception.TokenException;
import com.liuweiheng.base.exception.UserException;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.validation.ValidationException;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局统一处理异常控制器
 *
 * @author lwh
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理用户已存在在异常（UserExistException)
     * @param e 用户已存在异常
     * @return R(400, 用户已存在)
     */
    @ExceptionHandler(UserException.class)
    @ResponseBody
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public R handlerUserExistException(UserException e) {
        return R.error(400, e.getMessage() + "：ID[" + e.getId() + "]");
    }


    /**
     * 处理接口幂等异常（TokenException)
     * @param e 用户已存在异常
     * @return R(400, token不存在)
     */
    @ExceptionHandler(TokenException.class)
    @ResponseBody
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public R handlerUserExistException(TokenException e) {
        return R.error(400, e.getMessage());
    }

    /**
     * 处理参数验证异常（MethodArgumentNotValidException）
     * @param e 参数验证异常
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R handlerValidationException(MethodArgumentNotValidException  e) {
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError)error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });
        return R.error(400, "Bad Request Param").putData(errors);
    }

}
